<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="素材编码" prop="id" >
        <el-input
          v-model="queryParams.id"
          placeholder="请输入素材编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图片名称" prop="imgName">
        <el-input
          v-model="queryParams.imgName"
          placeholder="请输入图片名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图片类别" prop="imgCategory">
        <el-input
          v-model="queryParams.imgCategory"
          placeholder="请输入图片类别"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="源类型" prop="imgType">
        <el-select v-model="queryParams.imgType" placeholder="请选择源类型" clearable @keyup.enter.native="handleQuery">
          <el-option label="PSD" value="1" />
          <el-option label="TIF" value="2" />
          <el-option label="TIFF" value="3" />
          <el-option label="CDR" value="4" />
          <el-option label="AI" value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="上传人" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择上传人" filterable clearable style="width: 240px" @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="toolbar">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-sell"
          @click="handleUploadDialog"
          v-hasPermi="['business:imgInfo:upload']"
        >云上传</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :disabled="multiple"
          icon="el-icon-sold-out"
          @click="handleDownloadDialog"
          v-hasPermi="['business:imgInfo:download']"
        >云下载</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:imgInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['business:imgInfo:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          @click="handleBatchDelete"
          v-hasPermi="['business:imgInfo:batchRemove']"
        >批量删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList">
        <template slot="default">
          <el-link :underline="false" type="success" style="margin-right: 10px;" @click="handleSuccessVectors">成功：{{successCount}}</el-link>
          <el-link :underline="false" type="danger" style="margin-right: 10px;" @click="handleFailVectors">失败：{{failCount}}</el-link>
        </template>
      </right-toolbar>
    </el-row>
    <div ref="divTable" :style="'height:' + divHeight + 'px'">
      <el-table ref="imgInfoTable" v-loading="loading" :data="imgInfoList" @selection-change="handleSelectionChange" row-key="id">
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true"/>
        <el-table-column label="缩略图" align="center" prop="imgPngPath" width="130">
          <template slot-scope="scope">
              <image-preview :src="getImageUrl(scope.row.imgFullPngUrl)" style="height: 100px;"/>
          </template>
        </el-table-column>
        <el-table-column label="源类型" align="center" prop="imgType" width="60">
          <template v-slot="scope">
            <el-tag>{{ imgTypeMap[scope.row.imgType] || '未知' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="编码" align="center" prop="id" width="230"/>
        <el-table-column label="名称" align="center" prop="imgName" show-overflow-tooltip />
        <el-table-column label="类别" align="center" prop="imgCategory" />
        <el-table-column label="源HASH值" align="center" prop="imgHash" show-overflow-tooltip />
        <el-table-column label="源大小" align="center" prop="imgSourceSize" width="100">
          <template v-slot="scope">
            <span>{{ $fileSize(scope.row.imgSourceSize) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="JPG大小" align="center" prop="imgJpgSize" width="100">
          <template v-slot="scope">
            <span>{{ $fileSize(scope.row.imgJpgSize) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="PNG大小" align="center" prop="imgPngSize" width="100">
          <template v-slot="scope">
            <span>{{ $fileSize(scope.row.imgPngSize) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="imgStatus" width="55">
          <template v-slot="scope">
            <dict-tag :options="dict.type.sys_status" :value="scope.row.imgStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="特征码状态" align="center" prop="imgVectorsStatus" width="90">
          <template v-slot="scope">
            <el-tag type="success" v-if="scope.row.imgVectorsStatus === 'SUCCESS'">成功</el-tag>
            <el-tag type="danger" v-if="scope.row.imgVectorsStatus === 'FAIL'">失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上传人" align="center" prop="userId" >
          <template v-slot="scope">
            <user-tag :value="scope.row.userId" type="userId"/>
          </template>
        </el-table-column>
        <el-table-column label="上传时间" align="center" prop="createTime" width="140">
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
        <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="150">
          <template slot-scope="scope">
            <el-button
                type="text"
                v-if="scope.row.imgStatus !== 'LOCKED'"
                :icon="scope.row.imgStatus === 'DELETED' ? 'el-icon-refresh-left' : 'el-icon-delete'"
                @click="handleChangeStatus(scope.row, 'delButton')"
                v-hasPermi="['business:imgInfo:changeStatus']"
            >{{scope.row.imgStatus === 'DELETED' ? "恢复" : "删除" }}</el-button>
            <el-button
              type="text"
              :icon="scope.row.imgStatus === 'LOCKED' ? 'el-icon-unlock' : 'el-icon-lock'"
              v-hasPermi="['business:imgInfo:changeStatus']"
              v-if="scope.row.imgStatus === 'NORMAL' || scope.row.imgStatus === 'LOCKED'"
              @click="handleChangeStatus(scope.row, 'lockButton')"
            >{{scope.row.imgStatus === 'LOCKED' ? "解锁" : "锁定" }}</el-button>
            <el-dropdown @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['business:imgInfo:editInfo', 'business:imgInfo:editSource', 'business:imgInfo:editJpg', 'business:imgInfo:editPng']">
              <el-button type="text" icon="el-icon-d-arrow-right">修改</el-button>
              <el-dropdown-menu v-slot="dropdown">
                <el-dropdown-item command="handleVectors" icon="el-icon-refresh"
                                  v-hasPermi="['business:imgInfo:editVectors']">生成特征码</el-dropdown-item>
                <el-dropdown-item command="handleEditInfo" icon="el-icon-info"
                                  v-hasPermi="['business:imgInfo:editInfo']">基本信息</el-dropdown-item>
                <el-dropdown-item command="handleEditSource" icon="el-icon-picture"
                                  v-hasPermi="['business:imgInfo:editSource']">源文件</el-dropdown-item>
                <el-dropdown-item command="handleEditJPG" icon="el-icon-picture-outline"
                                  v-hasPermi="['business:imgInfo:editJpg']">JPG</el-dropdown-item>
                <el-dropdown-item command="handleEditPNG" icon="el-icon-picture-outline-round"
                                  v-hasPermi="['business:imgInfo:editPng']">PNG</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <div class="selected-count" v-show="ids.length > 0">
          已勾选：{{ ids.length }} 条数据
        </div>
        <div class="pagination-wrapper">
          <pagination
            v-show="total > 0"
            :pageRefs="this.$refs"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="() => getList(queryParams.imgVectorsStatus)"
          />
        </div>
      </div>
    </div>

    <!-- 云下载对话框 -->
    <download-dialog ref="downloadDialog" :visible.sync="downloadVisible" :imgList="imgDownloadInfoList" @close="handleDownloadDialogClose" />

    <!-- 云上传对话框 -->
    <upload-dialog ref="uploadDialog" :visible.sync="uploadVisible" @close="handleUploadDialogClose"  @refreshTable="refresh"/>

    <!-- 修改对话框 -->
    <edit-dialog ref="editDialog" @refreshTable="refresh"/>

    <el-dialog title="批量删除" :visible.sync="batchRemoveOpen" width="500px" append-to-body>
      <el-alert title="注意" type="error" description="此操作不可逆，会同步删除素材文件，请慎重操作！！！" show-icon :closable="false" />
      <el-input type="textarea" :rows="10" placeholder="请输入素材编号，多个用英文逗号隔开" v-model="dialogInput" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBatchRemoveSubmit">确 定</el-button>
        <el-button @click="batchRemoveOpen=false;dialogInput=null">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listImgInfo,
  exportExcel,
  updateChangeStatus,
  delImgInfo,
  getVectorsCount,
  updateImgInfo,
  batchRemove
} from "@/api/business/imgInfo";
import {getNormalUserInfo} from "@/api/system/user";
import ResizeMixin from "@/layout/mixin/ResizeHandler";
import downloadDialog from "./downloadDialog"
import uploadDialog from "./uploadDialog.vue"
import editDialog from "./editDialog.vue";

export default {
  name: "ImgInfo",
  mixins: [ResizeMixin],
  dicts: ['sys_status'],
  components: { downloadDialog, uploadDialog, editDialog},
  data() {
    return {
      // div高度
      divHeight: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 业务-素材信息表格数据
      imgInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        id: null,
        pageNum: 1,
        pageSize: 10,
        imgName: null,
        imgCategory: null,
        imgType: null,
        imgStatus: null,
        imgVectorsStatus: null,
      },
      imgTypeMap: {
        '1': 'PSD',
        '2': 'TIF',
        '3': 'TIFF',
        '4': 'CDR',
        '5': 'AI'
      },
      // 云下载对话框
      downloadVisible: false,
      // 云下载表格数据
      imgDownloadInfoList: [],
      // 云下载遮罩层
      imgDownloadLoading: true,
      // 云上传对话框
      uploadVisible: false,
      // 特征码成功个数
      successCount: 0,
      // 特征码失败个数
      failCount: 0,
      // 用户选项
      userOptions: [],
      // 批量删除对话框
      batchRemoveOpen: false,
      // 批量删除输入框
      dialogInput: null,
    };
  },
  created() {
    this.getList();
    this.getUserList();
    this.getPngVectorsCount()
  },
  methods: {
    /** 刷新方法 */
    refresh() {
      this.getList();
      this.getPngVectorsCount();
    },
    /** 查询特征码成功失败个数 */
    getPngVectorsCount() {
      getVectorsCount().then(res => {
        if (res.data){
          const data = res.data;
          this.successCount = data.success_count;
          this.failCount = data.fail_count;
        }

      });
    },
    /** 查询业务-素材信息列表 */
    getList(status) {
      this.loading = true;
      if (status !== undefined) {
        this.queryParams.imgVectorsStatus = status;
      }

      listImgInfo(this.queryParams).then(response => {
        this.imgInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        imgName: null,
        imgCategory: null,
        bucketUrl: null,
        imgSourcePath: null,
        imgJpgPath: null,
        imgPngPath: null,
        imgType: null,
        imgHash: null,
        imgSourceSize: null,
        imgJpgSize: null,
        imgPngSize: null,
        imgVectors: null,
        imgStatus: null,
        imgVectorsStatus: null,
        userId: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null
      };
      this.$resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getPngVectorsCount();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.imgVectorsStatus = null
      this.$resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.imgDownloadInfoList = selection
    },
    /** 导出按钮操作 */
    handleExport() {
      const exportParams = {
        ...this.queryParams,
        id: this.generateIdString()
      }
      exportExcel(exportParams)
    },
    /** 生成id */
    generateIdString(){
      let idString = '';

      if (this.queryParams.id) {
        idString = this.queryParams.id;
      }

      if (this.ids && this.ids.length > 0) {
        if (idString) {
          idString += ',' + this.ids.join(',');
        } else {
          idString = this.ids.join(',');
        }
      }

      return idString || null;
    },
    /** 解锁或锁定按钮操作 */
    handleChangeStatus(row, type ) {
      const ids = row.id || this.ids;
      let status = type === 'delButton' ? (row.imgStatus === 'NORMAL' || row.imgStatus === 'LOCKED' ? '删除' : '恢复') : (row.imgStatus === 'LOCKED' ? '解锁' : '锁定');
      this.$modal.confirm('是否确认' + status + row.imgName + '的数据项？').then(function() {
        row.imgStatus = type === 'delButton' ? (row.imgStatus === 'NORMAL' || row.imgStatus ==='LOCKED' ? 'DELETED' : 'NORMAL') : (row.imgStatus === 'LOCKED' ? 'NORMAL' : 'LOCKED');
        return updateChangeStatus(ids, row.imgStatus)
      }).then(() => {
        this.getList();
        this.getPngVectorsCount();
        this.$modal.msgSuccess(row.imgName + status + "成功");
      }).catch(() => {});
    },
    /** 云下载按钮操作 */
    handleDownloadDialog(){
      this.downloadVisible = true;
    },
    /** 云下载弹出框关闭 */
    handleDownloadDialogClose(){
      this.downloadVisible = false;
      this.imgDownloadInfoList = [];
      // 清空表格选中
      this.$refs.imgInfoTable.clearSelection();
    },
    /** 云上传按钮操作 */
    handleUploadDialog(){
      this.uploadVisible = true;
    },
    /** 云上传弹出框关闭 */
    handleUploadDialogClose(){
      this.uploadVisible = false;
    },
    /** 真删除 */
    handleDelete(row){
      const ids = row.id || this.ids;
      this.$modal.confirm('注意：此删除不可恢复，是否确认删除？').then(function() {
        return delImgInfo(ids)
      }).then(() => {
        // 手动更新列表
        this.imgInfoList = this.imgInfoList.filter(item => !ids.includes(item.id));
        // 清空表格选中
        this.$refs.imgInfoTable.clearSelection();
        this.getList();
        this.getPngVectorsCount();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 修改操作触发 */
    handleCommand(command, row) {
      switch (command) {
        case "handleVectors":
          this.handleVectors(row);
          break;
        case "handleEditInfo":
          this.handleUpdate(row, 'info');
          break;
        case "handleEditSource":
          this.handleUpdate(row, 'Source');
          break;
        case "handleEditJPG":
          this.handleUpdate(row, 'Jpg');
          break;
        case "handleEditPNG":
          this.handleUpdate(row, 'Png');
          break;
        default:
          break;
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      const id = row.id || this.ids
      this.$refs.editDialog.setIdAndType(id, type);
    },
    /** 生成图片 URL 并添加时间戳 */
    getImageUrl(imgFullPngUrl) {
      const timestamp = new Date().getTime();
      return `${imgFullPngUrl}?t=${timestamp}`;
    },
    /** 特征码成功个数按钮 */
    handleSuccessVectors(){
      this.queryParams.pageNum = 1; // 重置页码
      this.getList('SUCCESS')
    },
    /** 特征码失败个数按钮 */
    handleFailVectors(){
      this.queryParams.pageNum = 1; // 重置页码
      this.getList('FAIL')
    },
    /** 重新生成特征码 */
    handleVectors(row){
      row.flag = 'UPDATE';
      updateImgInfo(row).then(response => {
        this.$modal.msgSuccess("生成中，请5分钟后刷新页面查看");
        this.getList();
        this.getPngVectorsCount();
      });
    },
    /** 获取用户集合 */
    getUserList(){
      getNormalUserInfo().then(response => {
        this.userOptions = response.data;
      });
    },
    /** 批量删除 */
    handleBatchDelete(){
      this.dialogInput = null;
      this.batchRemoveOpen = true;
    },
    /** 批量删除确认 */
    handleBatchRemoveSubmit(){
      const ids = this.dialogInput
        ? this.dialogInput.split(',').map(item => item.trim()).filter(item => item)
        : [];
      if (ids.length === 0) {
        this.$modal.msgWarning("请输入有效的素材编号");
        return;
      }
      delImgInfo(ids).then(response => {
        this.batchRemoveOpen = false;
        this.$modal.msgSuccess("删除成功");
        this.getList();
        this.getPngVectorsCount();
      });
    }
  },
};
</script>
<style lang="postcss" scoped>
/deep/ .el-image__inner{
  object-fit: contain !important;
}

.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  padding: 8px 0;
}

.selected-count {
  font-size: 14px;
  color: #666;
}

.pagination-wrapper {
  text-align: right;
}
</style>
